<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\ocean;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\model\ClientAccountModel;
use app\model\OeProjectPromotionModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\fetch\MediaService;
use app\service\ocean\AdvertiserService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Cache;
use think\Model;

class PromotionService extends MediaService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[OceanEnum::LIST_CONFIG_LOCK_KEY]['promotion_list'];

    /**
     * 获取广告列表.
     *
     * @param string $advertiserId 广告主id
     */
    public static function getPromotionList(string $advertiserId = ''): bool
    {
        try {
            $redis = Cache::store('redis')->handler();
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            $page = 0;
            while (true) {
                $result = self::getList($advertiserId, ++$page);
                if ($result === false) {
                    return false;
                }
                if (count($result['data']['list']) == 0) {
                    break;
                }
                foreach ($result['data']['list'] as $item) {
                    $model = self::getInfo($advertiserId, $obj->getKey(), strval($item['project_id']), strval($item['promotion_id']));
                    if (! $model instanceof OeProjectPromotionModel || ! $model->getKey()) {
                        $model = new OeProjectPromotionModel();
                    }
                    $item['account_id'] = $obj->getKey();
                    $item['client_id'] = $obj->getAttr('client_id');
                    $item['advertiser_id'] = $advertiserId;
                    if (! $item['promotion_create_time']) {
                        $item['stat_date'] = date('Ymd', time());
                    } else {
                        $item['stat_date'] = date('Ymd', strtotime($item['promotion_create_time']));
                    }
                    $model->setAttrs($item);
                    if (! $model->save()) {
                        throw new \Exception('保存广告信息出错');
                    }

                    // 加入素材使用刷新队列
                    $redis->rPush(ConfigEnum::CACHE_CONFIG[OceanEnum::BATCH_CONFIG_KEY]['mongo_oe_material_use'], $model->getKey());
                }
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 拉取广告列表.
     *
     * @param string $advertiserId 账户id
     * @param int $page 分页
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', int $page = 1)
    {
        $token = AccountService::getToken(CommonEnum::OE_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'page' => $page,
            //            'page_size' => OeEnum::MAX_CUSTOM_MATERIAL_PAGE_SIZE,
        ];
        return AdvertiserService::getPromotionList($headers, $params);
    }

    /**
     * 获取广告信息.
     *
     * @param string $advertiserId 账户id
     * @param int $accountId 账户表id
     * @param string $projectId 项目id
     * @param string $promotionId 广告id
     * @return null|array|mixed|Model|OeProjectPromotionModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $advertiserId = '', int $accountId = 0, string $projectId = '', string $promotionId = '')
    {
        $where = [
            ['project_id', '=', $projectId],
            ['account_id', '=', $accountId],
            ['advertiser_id', '=', $advertiserId],
            ['promotion_id', '=', $promotionId],
        ];

        return (new OeProjectPromotionModel())->where($where)->field(true)->find();
    }
}
